package com.aaa.security;


import com.aaa.entity.Role;

import com.aaa.entity.User;
import com.aaa.service.RoleService;
import com.aaa.service.UserService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Repository;

import javax.annotation.Resource;
import java.util.List;

@Repository
public class UserDetailsServiceImpl implements UserDetailsService{
    @Resource
    RoleService roleService;
    @Resource
    UserService userService;
    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
        System.out.println("s:"+s);
        QueryWrapper<User> empQueryWrapper = new QueryWrapper<>();
        empQueryWrapper.eq("username",s);
        List<User> list = userService.list(empQueryWrapper);
        if (list.size()==1){

            System.out.println(list.get(0));
            User user=list.get(0);
          //查询用户的角色
//            StringBuffer str=new StringBuffer();
//            if(s.equals("zs")){
//                str.append("ROLE_ADMIN,ADMIN,add,update,delete,select");
//            }else {
//                str.append("ROLE_USER,ROLE_TEST,TEST,select");
//            }
            Role role=roleService.getById(user.getRid());
            StringBuffer str=new StringBuffer();
            str.append(role.getRolename());

            //设置权限
            if(s.equals("lipengfei")){
                //将字符串按照逗号隔开，转换为权限列表
                //ROLE_角色，add,update权限
                str.append(",count,list,getById");
            }else {
                str.append(",list");
            }
            user.setAuthorties(AuthorityUtils.commaSeparatedStringToAuthorityList(str.toString()));
            return list.get(0);
        }else {
            new UsernameNotFoundException("空");
            return null;
        }
    }
}
